import React, { useEffect, useState, useContext } from "react";
import {
  View,
  StyleSheet,
  StatusBar,
  SafeAreaView,
  Text,
  Dimensions,
  Image,
  TouchableOpacity,
  TouchableHighlight,
  Alert,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";
import { Feather } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import { SwipeListView } from "react-native-swipe-list-view";
import LoadingBar from "../../components/InterView/LoadingBar";
import InterviewContext from "../../context/interview/InterviewContext";

const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window");

const InterviewList = ({ route, navigation }) => {
  const type = route.params.type;
  const { interviewList, deleteInterview } = useContext(InterviewContext);

  const [typeList, setTypeList] = useState([]);
  //List形式还是Grid形式
  const [isList, setIsList] = useState(true);
  //无内容显示没有文件
  const [hasContent, setHasContent] = useState(false);
  //control控制跳转
  const [selectTag, setSelectTag] = useState(2);
  //删除Loading
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      const typeinterviewList = interviewList.filter(
        (item) => item.type === type
      );
      setTypeList(typeinterviewList);
      if (typeinterviewList.length != 0) {
        setHasContent(true);
      } else {
        setHasContent(false);
      }
    }
    return () => {
      isMounted = false;
    };
  }, [interviewList]);

  //关闭行
  const closeRow = (rowMap, rowKey) => {
    if (rowMap[rowKey]) {
      rowMap[rowKey].closeRow();
    }
  };

  //删除行
  const deleteRow = (rowMap, rowKey) => {
    setIsLoading(true);
    const deleteData = typeList.filter((item) => item._id == rowKey);
    deleteInterview(deleteData[0], () => {
      setIsLoading(false);
    });
  };

  const renderItem = (rowData) => (
    <TouchableHighlight
      activeOpacity={0.6}
      underlayColor="#F7F7F7"
      style={{ height: 70, width: DEVICE_WIDTH, marginBottom: 10 }}
      onPress={() => {
        navigation.navigate("InterviewDetail", {
          _id: rowData.item._id,
        });
      }}
    >
      <View style={styles.item}>
        <View style={styles.itemleft}>
          <Image
            style={styles.itemIcon}
            source={require("../../../assets/interview/folder.png")}
          />
          <View>
            <Text style={styles.itemTitle}>{rowData.item.fileName}</Text>
            <View style={{ flexDirection: "row" }}>
              <Text style={styles.itemTime}>{rowData.item.date}</Text>
              <Text style={styles.itemTime}>{rowData.item.time}</Text>
            </View>
          </View>
        </View>
        <View>
          <AntDesign name="right" size={20} color="#c4c4c4" />
        </View>
      </View>
    </TouchableHighlight>
  );

  const renderHiddenItem = (data, rowMap) => (
    <View style={styles.rowBack}>
      <TouchableOpacity
        style={[styles.backRightBtn, styles.backRightBtnLeft]}
        onPress={() => closeRow(rowMap, data.item._id)}
      >
        <Image
          style={{ width: 30, height: 30 }}
          resizeMode="contain"
          source={require("../../../assets/interview/back.png")}
        />
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.backRightBtn, styles.backRightBtnRight]}
        onPress={() => {
          closeRow(rowMap, data.item._id);
          Alert.alert("提示", "要删除" + data.item.fileName + "吗?", [
            {
              text: "取消",
              style: "cancel",
            },
            {
              text: "确定",
              onPress: () => {
                deleteRow(rowMap, data.item._id);
              },
            },
          ]);
        }}
      >
        <Image
          style={{ width: 30, height: 30 }}
          resizeMode="contain"
          source={require("../../../assets/interview/delete.png")}
        />
      </TouchableOpacity>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      <LoadingBar visible={isLoading} />

      <View style={styles.head}>
        <TouchableOpacity
          onPress={() => {
            navigation.goBack();
          }}
        >
          <AntDesign name="arrowleft" size={27} color="#2b2b2b" />
        </TouchableOpacity>

        <View style={styles.icons}>
          <TouchableOpacity
            onPress={() => {
              navigation.navigate("InterviewAdd", {
                type: type,
              });
            }}
          >
            <Feather
              name="folder-plus"
              size={27}
              color="#2b2b2b"
              style={{ marginRight: 15 }}
            />
          </TouchableOpacity>

          <TouchableOpacity
            onPress={() => {
              setIsList(!isList);
            }}
          >
            {isList ? (
              <Feather name="grid" size={27} color="#2b2b2b" />
            ) : (
              <MaterialIcons
                name="format-list-bulleted"
                size={27}
                color="#2b2b2b"
              />
            )}
          </TouchableOpacity>
        </View>
      </View>

      <View style={styles.control}>
        <TouchableOpacity
          onPress={() => {
            setSelectTag(1);
            navigation.navigate("InterviewType");
          }}
        >
          <View
            style={[
              selectTag == 2 ? styles.unselectedTag : styles.selectedTag,
              { marginRight: 10 },
            ]}
          >
            <Text
              style={
                selectTag == 2
                  ? styles.unselectedTagText
                  : styles.selectedTagText
              }
            >
              访谈类型
            </Text>
          </View>
        </TouchableOpacity>

        <AntDesign
          name="right"
          size={17}
          color="#d6d6d6"
          style={{ marginRight: 10 }}
        />

        <TouchableOpacity
          onPress={() => {
            setSelectTag(2);
          }}
        >
          <View
            style={selectTag == 2 ? styles.selectedTag : styles.unselectedTag}
          >
            <Text
              style={
                selectTag == 2
                  ? styles.selectedTagText
                  : styles.unselectedTagText
              }
            >
              {type}
            </Text>
          </View>
        </TouchableOpacity>
      </View>

      {hasContent ? (
        <View>
          {isList ? (
            <SwipeListView
              useFlatList={true}
              data={typeList}
              keyExtractor={(item) => item._id}
              renderItem={renderItem}
              renderHiddenItem={renderHiddenItem}
              rightOpenValue={-150}
              onRowOpen={(rowKey, rowMap) => {
                setTimeout(() => {
                  rowMap[rowKey] && rowMap[rowKey].closeRow();
                }, 5000);
              }}
            />
          ) : (
            <View style={styles.fileGrid}>
              {typeList.map((fileItem, index) => {
                return (
                  <TouchableOpacity
                    key={index}
                    onPress={() => {
                      navigation.navigate("InterviewDetail", {
                        _id: fileItem._id,
                      });
                    }}
                  >
                    <View
                      style={
                        index % 4 == 3 ? styles.lascolFileItem : styles.fileItem
                      }
                    >
                      <Image
                        style={styles.fileIcon}
                        source={require("../../../assets/interview/folder.png")}
                      />
                      <Text>{fileItem.fileName}</Text>
                    </View>
                  </TouchableOpacity>
                );
              })}
            </View>
          )}
        </View>
      ) : (
        <View style={styles.nullfile}>
          <Image
            style={styles.nullFileIcon}
            source={require("../../../assets/interview/nullfile.jpg")}
          />
          <View>
            <Text style={styles.nullFileText}>没有文件</Text>
          </View>
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
    backgroundColor: "#FFFFFF",
  },
  head: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginHorizontal: 20,
    marginVertical: 15,
  },
  icons: {
    flexDirection: "row",
  },
  control: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-start",
    marginLeft: 20,
    marginBottom: 15,
  },
  selectedTag: {
    borderWidth: 1,
    borderRadius: 15,
    borderColor: "transparent",
    backgroundColor: "#fff6d9",
    paddingHorizontal: 12,
    paddingVertical: 3,
  },
  selectedTagText: {
    color: "#e7b92c",
    fontSize: 15,
  },
  unselectedTag: {
    borderWidth: 1,
    borderRadius: 15,
    borderColor: "transparent",
    backgroundColor: "#f1f2f6",
    paddingHorizontal: 12,
    paddingVertical: 3,
  },
  unselectedTagText: {
    color: "#898aa3",
    fontSize: 15,
  },
  item: {
    height: 70,
    width: DEVICE_WIDTH,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingLeft: 20,
    paddingRight: 20,
    backgroundColor: "#ffffff",
  },
  itemleft: {
    flexDirection: "row",
    justifyContent: "flex-start",
    alignItems: "center",
  },
  itemIcon: {
    width: 50,
    height: 55,
    marginRight: 20,
  },
  itemTitle: {
    fontSize: 16,
    fontWeight: "bold",
    marginBottom: 3,
  },
  itemTime: {
    fontSize: 14,
    color: "#888",
    marginRight: 10,
  },
  fileGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "flex-start",
    alignContent: "space-between",
    marginHorizontal: 20,
  },
  fileItem: {
    width: (DEVICE_WIDTH - 40) / 5,
    marginRight: (DEVICE_WIDTH - 40) / 15,
    marginBottom: DEVICE_WIDTH / 20,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
  lascolFileItem: {
    width: (DEVICE_WIDTH - 40) / 5,
    marginBottom: DEVICE_WIDTH / 20,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
  fileIcon: {
    width: 50,
    height: 55,
  },
  rowBack: {
    alignItems: "center",
    backgroundColor: "#ffffff",
    flex: 1,
    flexDirection: "row",
    justifyContent: "flex-end",
    paddingLeft: 15,
    marginBottom: 10,
  },
  backRightBtn: {
    alignItems: "center",
    bottom: 0,
    justifyContent: "center",
    position: "absolute",
    top: 0,
    width: 75,
  },
  backRightBtnLeft: {
    backgroundColor: "#ffd",
    right: 75,
  },
  backRightBtnRight: {
    backgroundColor: "#ffd8d5",
    right: 0,
  },
  backTextWhite: {
    color: "#FFF",
  },
  nullfile: {
    flex: 1,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
  nullFileIcon: {
    width: 100,
    height: 100,
    marginBottom: 10,
  },
  nullFileText: {
    fontSize: 16,
    paddingLeft: 8,
    color: "#989898",
  },
});

export default InterviewList;
